<template>
    <div ref="refChart" style="width: 100%; height: 170px"></div>
</template>

<script lang="ts" setup>
import {onUnmounted, onMounted, ref} from 'vue';
import * as echarts from 'echarts';
import { RequestStatisticGetPieChartData } from "@/api/path/index.js";
type EChartsOption = echarts.EChartsOption;
const refChart = ref();
const chartInstance = ref();
const chartData = ref([])
// 获取接口数据
const getData= ()=>{
  return new Promise((resolve, reject)=>{
    RequestStatisticGetPieChartData().then((res:any)=>{
      res.resultObj.forEach((item: any) => {
        delete item.measure
      })
      chartData.value = res.resultObj
      resolve(res.resultObj)
    })
      .catch((err:any)=>{
        reject(err)
      })
  })

}
onMounted(async ()=>{
  await getData()
  // 图表初始化
  initChart();
  // 调用Echarts图表自适应方法
  screenAdapter();
  // Echarts图表自适应
  window.addEventListener("resize", screenAdapter);
})
const initChart=()=>{
  chartInstance.value = echarts.init(refChart.value);
  const initOption:EChartsOption = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        bottom: 'center',
        right:'2.5rem',
        textStyle:{
          lineHeight:30
        },
         // left: 'right',
      },
      color: ['#017efa', '#b1cbfe', '#51cbff', '#b6e9ff'],
      series: [
        {
          name: '拆解资源占比',
          type: 'pie',
          radius: ['40%', '60%'],
          center: ['30%', '50%'],
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: chartData.value
        }
      ]
  }
    // 图表初始化配置
    chartInstance.value?.setOption(initOption);
}
const screenAdapter=()=>{
  // 手动的调用图表对象的resize 才能产生效果
  chartInstance.value.resize({width:'auto', animation: { duration: 300 } });
}
onUnmounted(() => {
  // 销毁Echarts图表
  chartInstance.value.dispose();
  chartInstance.value = null;
  // Echarts图表自适应销毁
  window.removeEventListener("resize", screenAdapter);
});

</script>